package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.oss.service.OssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFile(MultipartFile file) {
        // Endpoint以北京华北1为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";// 域名地址

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。
        // 强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tQmVmyVnGSU1ithmHeH";
        String accessKeySecret = "3qLE0wnaarLtw4zvrAAFMMp3yVPVw7";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "beijng1031";

        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = new DateTime().toString("yyyy/MM/dd")+"/"+ UUID.randomUUID().toString().replace("_","")+file.getOriginalFilename();
            //创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, originalFilename, inputStream);
            putObjectRequest.setProcess("true"); //设置该属性可以返回response,不设置返回为空
            //创建PutObject对象
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            return "https://"+bucketName+"."+endpoint+"/"+originalFilename;
        } catch (IOException e) {
            e.printStackTrace();
            throw new YYGHException(20001,"上传失败");

        } finally {
            if(ossClient !=null){
                ossClient.shutdown();
            }
        }
    }
}